<?php

namespace app\admin\controller\news;

use app\common\controller\Backend;
use app\common\model\News as ModelNews;
use app\common\model\NewsCategory;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class News extends Backend
{
    protected $multiFields = 'is_release';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('News');
        $action = $this->request->action();
        if ($action == 'add' || $action == 'edit') {
            $this->assign("cateList", model('NewsCategory')->where('status', NewsCategory::STATUS_TWO)->order('weigh desc, id desc')->column('id,name'));
        }
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->model = model('News');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(['id', 'title'], true);
            $total = $this->model
                ->with(['category'])
                ->where($where)
                ->count();

            $list = $this->model
                ->with(['category'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            foreach ($list as &$item) {
                $item['content'] = mb_substr(strip_tags($item['content']), 0, 30) . "...";
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        $this->model = model('News');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    $this->model->validateFailException(true)->validate('app\common\validate\News.add');
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } else {
            $this->assign('typeList', $this->getTypeList());
        }
        return $this->view->fetch();
    }

    public function edit($ids = '')
    {
        $this->model = model('News');
        $row = $this->model->get($ids);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $row->validateFailException(true)->validate('app\common\validate\News.edit');
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        } else {
            $this->assign('typeList', $this->getTypeList());
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = '')
    {
        $this->model = model('News');
        parent::del($ids);
    }

    protected function getTypeList()
    {
        return [
            ModelNews::TYPE_TEXT => __('Type editor'),
            ModelNews::TYPE_HANG => __('Type hang'),
        ];
    }


    /**
     * 批量发布或批量下架
     */
    public function checkids()
    {
        $lists = json_decode($this->request->param('ids',[]),true);
        $is_release = $this->request->param('is_release/d',1);
        $res = ModelNews::where('id','in',$lists)->update(['is_release'=>$is_release,'update_time'=>time()]);
        if($res){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }
}
